{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "13e61b48",
   "metadata": {},
   "source": [
    "# Numpy\n",
    "\n",
    "- NumPy(Numerical Python)是一个开源的Pythoni科学计算库，用于快速处理任意维度的数组。\n",
    "- NumPy支持常见的数组和矩阵操作。对于同样的数值计算任务，使用Numpy比直接使用Python要简洁的多。\n",
    "- NumPy使用ndarray对象来处理多维数组，该对象是一个快速而灵活的大数据容器。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ac566e3",
   "metadata": {},
   "source": [
    "- Why NumPy? \n",
    "  - 快速\n",
    "  - 方便\n",
    "  - 科学计算的基础库\n",
    "\n",
    "-  NumPy的优势\n",
    "   - 对于同样的数值计算任务，使用NumPy要比直接编写Python代码便捷得多；\n",
    "   - NumPy中的数组的存储效率和输入输出性能均远远优于Python中等价的基本数据结构，且其能够提升的性能是与数组中的元素成比例的；\n",
    "   - NumPy的大部分代码都是用C语言写的，其底层算法在设计时就有着优异的性能，这使得NumPy比纯Python代码高效得多。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d6413b3",
   "metadata": {},
   "source": [
    "## Numpy 的安装和导入\n",
    "\n",
    "- Numpy 安装： pip install numpy\n",
    "\n",
    "- 导入：`import numpy as np`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b948d960",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "92d6b552",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'1.20.3'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.__version__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5753d9ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0019936561584472656 0.0009987354278564453\n"
     ]
    }
   ],
   "source": [
    "# Ndarray 和 list 运算速度比较\n",
    "\n",
    "import random\n",
    "import time\n",
    "\n",
    "a = []\n",
    "for i in range(100000):\n",
    "    a.append(random.random())\n",
    "t1 = time.time()\n",
    "sum1 = sum(a)  # 求和\n",
    "t2 = time.time()\n",
    "\n",
    "b=np.array(a)\n",
    "t4=time.time()\n",
    "sum3=np.sum(b)\n",
    "t5=time.time()\n",
    "print(t2-t1,t5-t4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2c9bed6e",
   "metadata": {},
   "source": [
    "## Numpy的Ndarray对象\n",
    "\n",
    "- **Numpy 最重要的一个特点是其 N 维数组对象 ndarray (ndarray stands for N dimensional array)，它是一系列<strong style=\"color:#c00000;\">同类型数据</strong>的集合。**\n",
    "\n",
    "    - 以0下标为开始进行集合中元素的索引\n",
    "    - ndarray对象是用于存放同类型元素的多维数组\n",
    "\n",
    "- 多维矩阵\n",
    "    - 1维数组看做向量 vector -- 点和直线\n",
    "    - 2维数组看做 2维矩阵 -- 表和平面\n",
    "    - 3维数组看做 3维矩阵\n",
    "    \n",
    "- Numpy 常用方法 — 矩阵和随机数生成\n",
    "\n",
    "    - `np.array`\n",
    "    - `np.arange` \n",
    "    - `np.linspace` \n",
    "    - `np.zeros` \n",
    "    - `np.ones`\n",
    "    - `np.full`\n",
    "    - `np.random` "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79a6df1a",
   "metadata": {},
   "source": [
    "### 一维数组"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ce1fa6d",
   "metadata": {},
   "source": [
    "#### 使用np.arange 生成ndarray\n",
    "\n",
    "- `np.arange()` 函数返回一个有终点和起点的固定步长的排列, 类型为numpy.ndarray, 可被当作向量使用\n",
    "  - `np.arange()` allows you to create an array that contains a range of evenly spaced intervals\n",
    "\n",
    "- 参数个数情况： `np.arange()`函数分为一个参数，两个参数，三个参数三种情况 \n",
    "\n",
    "    - 一个参数时，参数值为终点，起点取默认值0，步长取默认值1。 \n",
    "\n",
    "    - 两个参数时，第一个参数为起点，第二个参数为终点，步长取默认值1。 \n",
    "\n",
    "    - 三个参数时，第一个参数为起点，第二个参数为终点，第三个参数为步长。其中步长支持小数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a8d6ab21",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1.  1.5 2.  2.5 3.  3.5 4.  4.5 5.  5.5 6.  6.5 7.  7.5 8.  8.5 9.  9.5]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "a=np.arange(1,10,0.5)\n",
    "print(a)\n",
    "print(type(a))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "325f3b4c",
   "metadata": {},
   "source": [
    "#### numpy.array   \n",
    "\n",
    "- 将 list 转化为ndarray类型\n",
    "- 传入range()生成序列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "46e43760",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 2 3 8 5]\n",
      "<class 'numpy.ndarray'>\n",
      "int32\n"
     ]
    }
   ],
   "source": [
    "a=np.array([1,2,3,8,5])\n",
    "print(a)\n",
    "print(type(a))\n",
    "print(a.dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "84931797",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 3 4 5 6 7 8 9]\n"
     ]
    }
   ],
   "source": [
    "a = np.array(range(10))\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd876a09",
   "metadata": {},
   "source": [
    "#### `np.linspace`  等差数列\n",
    "- `np.linspace(start, stop, num=50, endpoint=True)`\n",
    "- 在指定的间隔[\"start\",\"stop\"]内均匀地返回“num”个等间距的样本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3494924f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.        ,  0.51282051,  1.02564103,  1.53846154,  2.05128205,\n",
       "        2.56410256,  3.07692308,  3.58974359,  4.1025641 ,  4.61538462,\n",
       "        5.12820513,  5.64102564,  6.15384615,  6.66666667,  7.17948718,\n",
       "        7.69230769,  8.20512821,  8.71794872,  9.23076923,  9.74358974,\n",
       "       10.25641026, 10.76923077, 11.28205128, 11.79487179, 12.30769231,\n",
       "       12.82051282, 13.33333333, 13.84615385, 14.35897436, 14.87179487,\n",
       "       15.38461538, 15.8974359 , 16.41025641, 16.92307692, 17.43589744,\n",
       "       17.94871795, 18.46153846, 18.97435897, 19.48717949, 20.        ])"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "np.linspace(0,20,40)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9801a388",
   "metadata": {},
   "outputs": [],
   "source": [
    "#指数图\n",
    "# import matplotlib.pyplot as plt\n",
    "# x=np.arange(-5,5,0.1)\n",
    "# y=np.power(2,x)   # y=2^x \n",
    "# #print(y)\n",
    "# plt.plot(x,y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "4cceec47",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "invalid literal for int() with base 10: 'Hey'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-24-159b15a347b8>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;31m# 可以改变元素取值， 但是不可以改变类型\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'Hey'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      3\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'Hey'"
     ]
    }
   ],
   "source": [
    "# 可以改变元素取值， 但是不可以改变类型\n",
    "a[4]='Hey'\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "c239517f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0, 15,  2,  3, 78,  5,  6,  7,  8,  9])"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 整数类型的ndarray，放入小数，截取小数点前整数\n",
    "a.dtype\n",
    "a[1]=15.89\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5854f284",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('float64')"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 设定元素类型\n",
    "a=np.array([1,2,3],dtype=float)\n",
    "a.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "a3b1af6b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 修改元素类型\n",
    "a.astype('int')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5bf98784",
   "metadata": {},
   "source": [
    "#### 将数组转换为列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "dc9959e2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1.0, 2.0, 3.0]\n",
      "[1.0, 2.0, 3.0]\n"
     ]
    }
   ],
   "source": [
    "a=np.array([1,2,3],dtype=float)\n",
    "print(list(a))\n",
    "\n",
    "a=np.array([1,2,3],dtype=float)\n",
    "print(a.tolist())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "36bc94b8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 2, 12, 36, 80, 150, 252, 392, 576, 810]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 练习：计算一个列表(list(range(n)))内元素的平方，加上相同列表内元素的立方\n",
    "# 写成函数形式，参数为n, 首先使用列表表达式操作\n",
    "\n",
    "def python_test(n):\n",
    "    #a=[i**2 for i in range(n)]\n",
    "    #b=[i**3 for i in range(n)]\n",
    "    c=[i**2+i**3 for i in range(n)]\n",
    "    return c\n",
    "\n",
    "python_test(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "b9bae1b3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  0,   2,  12,  36,  80, 150, 252, 392, 576, 810], dtype=int32)"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def numpy_test(n):\n",
    "    a=np.arange(n)**2\n",
    "    b=np.arange(n)**3\n",
    "    c=a+b\n",
    "    return c\n",
    "\n",
    "numpy_test(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "c49c2623",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 131 ms\n"
     ]
    }
   ],
   "source": [
    "# 测试运行时间\n",
    "\n",
    "%time res = python_test(100000)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "687dfb4a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 3.99 ms\n"
     ]
    }
   ],
   "source": [
    "%time res = numpy_test(100000)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cae5475",
   "metadata": {},
   "source": [
    "### 二维数组（矩阵）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "5b5ebf74",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2],\n",
       "       [2, 4]])"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 二维数组\n",
    "np.array([[1,2],[2,4]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5db9da1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 一些生成特殊矩阵的方法\n",
    "# np.zeros(num)\n",
    "np.zeros(10)\n",
    "# np.zeros(shape=(n1,n2)) \n",
    "np.zeros(shape=(3,3))\n",
    "# np.zeros(3,3) 报错"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "e1ccfc1a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 1., 1.],\n",
       "       [1., 1., 1.],\n",
       "       [1., 1., 1.],\n",
       "       [1., 1., 1.]])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.ones()\n",
    "np.ones(10)\n",
    "np.ones((4,3))\n",
    "# np.ones(shape = (4,3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "667c3564",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[9, 9],\n",
       "       [9, 9],\n",
       "       [9, 9],\n",
       "       [9, 9],\n",
       "       [9, 9]])"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.full()\n",
    "np.full((5,2),9)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "168fff8b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1., 0., 0.],\n",
       "       [0., 1., 0.],\n",
       "       [0., 0., 1.]])"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.identity()  创建单位矩阵\n",
    "np.identity(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "bc637c94",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[3, 0, 0],\n",
       "       [0, 2, 0],\n",
       "       [0, 0, 7]])"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.diag([1,2,3,4]) 根据一个向量创建斜对角方阵\n",
    "np.diag([3,2,7])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06281f7b",
   "metadata": {},
   "source": [
    "## Ndarray的常用属性"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ccdaf96",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 1  2]\n",
      " [ 5  4]\n",
      " [10  9]]\n",
      "2\n",
      "(3, 2)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "\n",
    "ls1 = [[1,2],[5,4],[10,9]]\n",
    "A = np.array(ls1)\n",
    "print(A)\n",
    "# ndarray.ndim : 维度 \n",
    "print(A.ndim)\n",
    "\n",
    "# ndarray.shape: 形状 （行，列）\n",
    "print(A.shape)\n",
    "\n",
    "# ndarray.size: 表示包含的元素总数 (属性)\n",
    "print(A.size)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b3706dd",
   "metadata": {},
   "source": [
    "## Numpy 数组的基础操作"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03476091",
   "metadata": {},
   "source": [
    "### 修改维度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "58e9ecb1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2]\n",
      " [3 7]\n",
      " [8 9]]\n",
      "[0 1 2 3 4 5 6 7 8 9]\n",
      "[[0 1 2 3 4]\n",
      " [5 6 7 8 9]]\n",
      "[0 1 2 3 4 5 6 7 8 9]\n",
      "[0 5 1 6 2 7 3 8 4 9]\n",
      "[0 1 2 3 4 5 6 7 8 9]\n",
      "[[[ 0  1  2  3]\n",
      "  [ 4  5  6  7]\n",
      "  [ 8  9 10 11]]\n",
      "\n",
      " [[12 13 14 15]\n",
      "  [16 17 18 19]\n",
      "  [20 21 22 23]]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(2, 3, 4)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.array([[1,2,3],[7,8,9]])\n",
    "\n",
    "# 修改原数组维度\n",
    "a.shape = (3,2)\n",
    "print(a)\n",
    "\n",
    "# ndarray.reshape 修改维度,返回一个新的数组\n",
    "a=np.arange(10)\n",
    "b=a.reshape(-1,5)  # a.reshape(2,5)\n",
    "print(a)\n",
    "print(b)\n",
    "# ndarray.reshape(n,-1)  or ndarray.reshape(-1,n)\n",
    "\n",
    "# 将多维变成一维数组\n",
    "a2 = b.reshape((10,), order = 'C')\n",
    "a3 = b.reshape((10,), order = 'F')\n",
    "# order默认为'C':以行为主的顺序展开，'F'(Fortran)意味着以列的顺序展开\n",
    "print(a2)\n",
    "print(a3)\n",
    "\n",
    "a4 = b.flatten() # order = 'F'\n",
    "print(a4)\n",
    "\n",
    "# 转为三维\n",
    "a = np.arange(24)\n",
    "a2 = a.reshape((2,3,4))\n",
    "print(a2)\n",
    "a2.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "5a282746",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "5e38baa0",
   "metadata": {},
   "source": [
    "### 取值操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "72009e60",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  1,  2,  3],\n",
       "       [ 4,  5,  6,  7],\n",
       "       [ 8,  9, 10, 11],\n",
       "       [12, 13, 14, 15]])"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A=np.arange(16).reshape(4,4)\n",
    "A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "id": "7dce9fee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "A[(0,0)]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ea5b695",
   "metadata": {},
   "source": [
    "### 切片"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "2b703070",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.arange(10)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "966bdef3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 4])"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[0:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "cb4d0a8e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2, 3, 4])"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[:5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "6c84f716",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([5, 6, 7, 8, 9])"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[5:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "957b9e2b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 2, 4, 6])"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[0:8:2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "id": "4ba94b12",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 2, 4, 6, 8])"
      ]
     },
     "execution_count": 90,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[::2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "639a7968",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a[::-1]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39861393",
   "metadata": {},
   "source": [
    "#### 二维数组的切片操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "7eebfa03",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  1,  2,  3,  4],\n",
       "       [ 5,  6,  7,  8,  9],\n",
       "       [10, 11, 12, 13, 14],\n",
       "       [15, 16, 17, 18, 19]])"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = np.arange(20).reshape(4,-1)\n",
    "X"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "0abd0e20",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 2, 4],\n",
       "       [5, 7, 9]])"
      ]
     },
     "execution_count": 96,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 前2行,0,2,4列\n",
    "X[0:2,::2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "e81e593d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[19, 18, 17, 16, 15],\n",
       "       [14, 13, 12, 11, 10],\n",
       "       [ 9,  8,  7,  6,  5],\n",
       "       [ 4,  3,  2,  1,  0]])"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X[::-1,::-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "2eb41599",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[5 6 7 8 9]\n",
      "[[ 5  6  7  8  9]\n",
      " [15 16 17 18 19]]\n"
     ]
    }
   ],
   "source": [
    "print(X[1])\n",
    "print(X[[1,3]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "59ea1d26",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0,  5, 10, 15],\n",
       "       [ 1,  6, 11, 16],\n",
       "       [ 2,  7, 12, 17],\n",
       "       [ 3,  8, 13, 18],\n",
       "       [ 4,  9, 14, 19]])"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#转置：ndarray.T\n",
    "X.T"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0aaaf5e5",
   "metadata": {},
   "source": [
    "### 数组中的数值修改"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "de6df5ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[10  1  2  3  4  5]\n",
      " [ 6  7  8  9 10 11]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "[[10  1  2  3  4  5]\n",
      " [20 20 20 20 20 20]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "[[10  0  0  0  0  0]\n",
      " [20 20 20 20 20 20]\n",
      " [12 13 14 15 16 17]\n",
      " [18 19 20 21 22 23]]\n",
      "[[0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0]\n",
      " [0 0 0 0 0 0]]\n",
      "[[False  True]\n",
      " [ True  True]\n",
      " [False  True]]\n",
      "(array([0], dtype=int64), array([1], dtype=int64))\n"
     ]
    }
   ],
   "source": [
    "t = np.arange(24).reshape(4,6)\n",
    "# 使用位置修改\n",
    "t[0,0] = 10\n",
    "print(t)\n",
    "\n",
    "# 修改一行\n",
    "t[1] = 20\n",
    "print(t)\n",
    "\n",
    "#可以根据条件修改，比如讲小于10的值改掉\n",
    "t[t<10]=0\n",
    "print(t)\n",
    "\n",
    "#使用逻辑判断\n",
    "# np.logical_and: &\n",
    "# np.logical_or: |\n",
    "# np.logical_not: ~\n",
    "\n",
    "t[(t>2)&(t<6)]=0  #与\n",
    "\n",
    "t[(t<2)|(t>6)]=6#或\n",
    "t[~(t>6)]=0 #非\n",
    "print(t)\n",
    "\n",
    "#拓展\n",
    "# 三目运算\n",
    "# (np.where(condition,X,y)满足条件(condition),输出x,不满足输出y.)\n",
    "\n",
    "score=np.array([[80,88],[82,81],[75,81]])\n",
    "result = np.where(score>80,True , False)\n",
    "print(result)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9e551770",
   "metadata": {},
   "source": [
    "## Numpy的数据类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "af60f7cc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "int16\n",
      "8\n",
      "[0.33 0.21 0.48 0.86 0.57 0.01 0.35 0.48 0.56 0.55]\n"
     ]
    }
   ],
   "source": [
    "a = np.array([1,2,3,4,5], dtype = np.int16)\n",
    "# 返回数组中每个元素的字节单位长度\n",
    "print(a.itemsize)\n",
    "print(a.dtype)\n",
    "\n",
    "# 调整数据类型\n",
    "a1 = a.astype(np.int64)\n",
    "print(a1.itemsize)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80c7b802",
   "metadata": {},
   "source": [
    "|名称|描述|简写|\n",
    "|:--|:--|:--|\n",
    "|np.bool | 用一个字节存储的布尔类型(True或False) |'b'|\n",
    "|np.int8 |一个字节大小，-128至127（一个字节）|'i'|\n",
    "|np.int16 | 整数，-32768至32767(2个字节) |'i2'|\n",
    "|np.int32 | 整数，$-2^31$至$2^31-1$(4个字节) | 'i4'|\n",
    "|np.int64 | 整数，$-2^63$至$2^63-1$(8个字节) |'i8' |\n",
    "|np.uint8| 无符号整数，0至255 |'u'|\n",
    "|np.uint16| 无符号整数，0至65535| 'u2'|\n",
    "|np.uint32 | 无符号整数，0至$2^32-1$ | 'u4' |\n",
    "|np.uint64 | 无符号整数，0至$2^64-1$ | 'u8' |\n",
    "|np.float16| 半精度浮点数：16位，正负号1位，指数5位，精度10位 |'f2'|\n",
    "|np.float32| 单精度浮点数：32位，正负号1位，指数8位，精度23位 |'f4'|\n",
    "|np.float64 |双精度浮点数：64位，正负号1位，指数11位，精度52位 |'f8'|\n",
    "|np.complex64|复数，分别用两个32位浮点数表示实部和虚部 |'c8'|\n",
    "|np.complex128| 复数，分别用两个64位浮点数表示实部和虚部|'c16'|\n",
    "|np.object |python对象 | 'O'|\n",
    "|np.string_ |字符串 |'S'|\n",
    "|np.unicode_ |unicode类型| 'U'|"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "246d7b48",
   "metadata": {},
   "source": [
    "## 数组的拼接"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69318be3",
   "metadata": {},
   "source": [
    "### 数组中的轴\n",
    "\n",
    "- 在Numpy中，轴可以理解为方向，使用0,1,2数字表示\n",
    "  - 对于一个一维数组，只有一个0轴\n",
    "  - 对于2维数组(shape(2,2)有0轴和1轴\n",
    "  - 对于3维数组(shape(2,2,3))有0,1,2轴\n",
    "  \n",
    "- 轴的作用：有了轴的概念后，我们计算会更加方便，比如计算一个2维数组的平均值，必须指定是计算哪个方向上面的数字的平均值。\n",
    "\n",
    "![](https://tingwen-pic.oss-cn-beijing.aliyuncs.com/img/20220407020422.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b26d3cd8",
   "metadata": {},
   "source": [
    "### 轴连接\n",
    "- 纵向连接，列数相同即可\n",
    "- 横向连接，行数相同即可"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "651c4f99",
   "metadata": {},
   "outputs": [],
   "source": [
    "X1 = np.array([[22, 168],\n",
    "               [18,187]])\n",
    "\n",
    "X2 = np.array([[0],\n",
    "               [1]])\n",
    "\n",
    "X3 = np.ones((2,1))\n",
    "X3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "00a7a3e8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 22., 168.,   0.,   1.],\n",
       "       [ 18., 187.,   1.,   1.]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print('沿轴1连接两个数组')\n",
    "np.concatenate([X1,X2,X3],axis=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9dfd70f0",
   "metadata": {},
   "source": [
    "- np.concatenate((a1, a2, …), axis=0) 数组拼接, 传入的参数必须是一个多个数组的元组或者列表\n",
    "\n",
    "  - 拼接的方向，默认是 axis = 0，对数组对象进行 纵向拼接（axis= 1 横向拼接）；\n",
    "\n",
    "  - 传入的数组必须具有相同的形状，这里的相同的形状可以满足在拼接方向axis轴上数组间的形状一致即可"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad30d4f7",
   "metadata": {},
   "source": [
    "### 堆叠和拼接\n",
    "\n",
    "- `np.stack((arr1,arr2), axis = 0)`\n",
    "  - 相同形状的数组沿着新轴连接数组的序列\n",
    "\n",
    "- `np.vstack` , `np.hstack`  矩阵垂直、水平拼接"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "a6130c62",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[ 1  2]\n",
      "  [11 12]]\n",
      "\n",
      " [[ 3  4]\n",
      "  [13 14]]]\n",
      "[[[ 1  2]\n",
      "  [ 3  4]]\n",
      "\n",
      " [[11 12]\n",
      "  [13 14]]]\n",
      "----------\n",
      "[[ 1  2]\n",
      " [ 3  4]\n",
      " [11 12]\n",
      " [13 14]]\n",
      "[[ 1  2 11 12]\n",
      " [ 3  4 13 14]]\n"
     ]
    }
   ],
   "source": [
    "a = np.array([[1,2],[3,4]])\n",
    "b = np.array([[11,12],[13,14]])\n",
    "\n",
    "# 根据轴进行堆叠\n",
    "print(np.stack((a,b), axis = 1))\n",
    "print(np.stack((a,b),axis = 0))\n",
    "print('-'*10)\n",
    "\n",
    "print(np.vstack((a,b)))\n",
    "print(np.hstack((a,b)))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3bd8c4c3",
   "metadata": {},
   "source": [
    "### 数组的分割\n",
    "\n",
    "- `np.split()`\n",
    "- `np.hsplit()`\n",
    "- `np.vsplit()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "ceb42f44",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "将数组分为三个大小相等的子数组：\n",
      "[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]\n",
      "原array:\n",
      "[[2. 0. 0. 9. 6. 7.]\n",
      " [9. 9. 4. 3. 7. 7.]]\n",
      "拆分后:\n",
      "[array([[2., 0.],\n",
      "       [9., 9.]]), array([[0., 9.],\n",
      "       [4., 3.]]), array([[6., 7.],\n",
      "       [7., 7.]])]\n",
      "[array([[2., 0., 0., 9., 6., 7.]]), array([[9., 9., 4., 3., 7., 7.]])]\n"
     ]
    }
   ],
   "source": [
    "#1.将一个数组分割为多个子数组\n",
    "# np.split(array,indices_or_sections, axis = 0)\n",
    "'''\n",
    "参数说明：\n",
    "array:被分割的数组\n",
    "indices_or_sections: 如果是一个整数，就用该数平均切分，如果是一个数组，为沿轴切分的位置（左开右闭）\n",
    "axis:沿着哪个维度进行切向，默认为0，横向切分。为1时，纵向切分\n",
    "'''\n",
    "\n",
    "a = np.arange(9).reshape(3,3)\n",
    "print('将数组分为三个大小相等的子数组：')\n",
    "b = np.split(a, 3)\n",
    "print (b)\n",
    "\n",
    "#2.numpy.hsplit函数用于水平分割数组，通过指定要返回的相同形状的数组数量来拆分原数组。\n",
    "\n",
    "a2 =  np.floor(10*np.random.random((2,6)))\n",
    "print('原array:')\n",
    "print(a2)\n",
    "print('拆分后:')\n",
    "print(np.hsplit(a2,3))\n",
    "#3.numpy.vsplit沿着垂直轴分割\n",
    "print(np.vsplit(a2,2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "386fbc01",
   "metadata": {},
   "source": [
    "## 数组的计算"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2111693d",
   "metadata": {},
   "source": [
    "### 数组和数的计算\n",
    "\n",
    "- 由于numpy的广播机机制在运算过程中，加减乘除的值被广播到所有的元素上面。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "a07228da",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  2  4  6  8]\n",
      " [10 12 14 16 18]]\n",
      "[[ 2  3  4  5  6]\n",
      " [ 7  8  9 10 11]]\n",
      "[[0.  0.5 1.  1.5 2. ]\n",
      " [2.5 3.  3.5 4.  4.5]]\n",
      "[[ 0  1  4  9 16]\n",
      " [25 36 49 64 81]]\n"
     ]
    }
   ],
   "source": [
    "a = np.arange(10).reshape(2,-1)\n",
    "print(a*2)\n",
    "print(a+2)\n",
    "print(a/2)\n",
    "print(a**2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1758b350",
   "metadata": {},
   "source": [
    "### 数组和数组的计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "f2444794",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[14 16 18]\n",
      " [20 22 24]]\n",
      "----------\n",
      "[[ 0 15 32]\n",
      " [51 72 95]]\n",
      "----------\n",
      "[[-14 -14 -14]\n",
      " [-14 -14 -14]]\n"
     ]
    }
   ],
   "source": [
    "# 形状相同的数组，对应数组内的元素进行相应计算\n",
    "\n",
    "a1 = np.arange(14,20).reshape(2,3)\n",
    "a2 = np.arange(6).reshape(2,3)\n",
    "print(a1+a2)\n",
    "print('-'*10)\n",
    "print(a1*a2)\n",
    "print('-'*10)\n",
    "print(a2-a1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fb04529e",
   "metadata": {},
   "source": [
    "```{Note}\n",
    "- 不同形状的多维数组不能计算！\n",
    "- BUT\n",
    "    - 行数或者列数相同的一维数组和多维数组可以进行计算：\n",
    "        - 行形状相同（会与每一行数组的对应位相操作）\n",
    "        - 列形状相同（会与每一列数组的对应位相操作）\n",
    "```\n",
    "\n",
    "![](https://tingwen-pic.oss-cn-beijing.aliyuncs.com/img/20220412001650.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "9769e43f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[-4 -4 -4 -4 -4 -4]\n",
      " [ 2  2  2  2  2  2]\n",
      " [ 8  8  8  8  8  8]\n",
      " [14 14 14 14 14 14]]\n",
      "[[ 0  1  2  3  4  5]\n",
      " [ 5  6  7  8  9 10]\n",
      " [10 11 12 13 14 15]\n",
      " [15 16 17 18 19 20]]\n"
     ]
    }
   ],
   "source": [
    "a1 = np.arange(24).reshape((4,6))\n",
    "a2 = np.arange(4,10)\n",
    "a3 = np.arange(4).reshape(4,1)\n",
    "\n",
    "print(a1-a2)\n",
    "print(a1 - a3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d64a0c90",
   "metadata": {},
   "source": [
    "### Numpy的计算方法 \n",
    "\n",
    "- np.nansum, np.nanmin, np.nanmax, np.round"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "27b69002",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.68 0.95 0.66 0.33 0.27 0.12 0.07 0.32 0.84 0.09]\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "a = np.array([random.random() for i in range(10)])\n",
    "# 保留小数\n",
    "print(np.round(a,2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "b4f7493f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2  3  4]\n",
      " [ 5  6  7  8  9]\n",
      " [10 11 12 13 14]]\n",
      "[10 35 60]\n",
      "7.0\n",
      "[0 0 0 1 2]\n",
      "[-2 -1  0  0  0]\n",
      "[-2 -2  0  1  2]\n",
      "[[1 2 3]\n",
      " [5 7 9]]\n",
      "[[ 1  3  6]\n",
      " [ 4  9 15]]\n",
      "0\n",
      "5\n",
      "[1.5 1.5 1.5]\n",
      "[0.81649658 0.81649658]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "3.5"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = np.arange(15).reshape(3, 5)\n",
    "print(X)\n",
    "# 求和\n",
    "# 在1轴上求和 （每行求和）\n",
    "print(np.sum(X,axis=1))\n",
    "# 在0轴上求和 （每列求和）\n",
    "np.sum(X,axis=0)\n",
    "\n",
    "# 求均值\n",
    "print(np.mean(X))  # 所有元素的均值\n",
    "np.mean(X,axis=0)\n",
    "\n",
    "# 获取某一轴上的最大、最小值\n",
    "np.max(X,axis = 0)  # 每一列的最大值\n",
    "\n",
    "np.min(X, axis = 0)\n",
    "\n",
    "# 数值的比较\n",
    "#第一个参数中的每一个数与第二个参数比较返回大的\n",
    "r = np.maximum([-2,-1,0,1,2], 0 )\n",
    "print(r)\n",
    "#第一个参数中的每一个数与第二个参数比较返回小的\n",
    "r = np.minimum([-2,-1,0,1,2], 0 )\n",
    "print(r)\n",
    "# 第一和第二个参数形状大小一样，逐一比较\n",
    "r = np.minimum([-2,-1,0,1,2], [0,-2,0,4,5] )\n",
    "print(r)\n",
    "\n",
    "# 累计和 cumsum\n",
    "a = np.array([1,2,3,4,5,6]).reshape(2,-1)\n",
    "print(a.cumsum(axis = 0))\n",
    "print(a.cumsum(axis = 1))\n",
    "\n",
    "# 最小/大值的索引： np.argmin, np.argmax\n",
    "print(np.argmin(a))\n",
    "print(np.argmax(a))\n",
    "\n",
    "# 计算标准差\n",
    "\n",
    "print(np.std(a,axis = 0))\n",
    "print(np.std(a,axis = 1))\n",
    "a.std(axis = 0)\n",
    "\n",
    "# 极值，np.ptp(array, axis = None), 最大值和最小值的差\n",
    "\n",
    "np.ptp(a)\n",
    "\n",
    "# 方差： var, cov, median\n",
    "np.mean(a)\n",
    "np.average(a)  # a.average() 不對\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44e32f99",
   "metadata": {},
   "source": [
    "#### 通用函数\n",
    "\n",
    "- TBD"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05dec8ed",
   "metadata": {},
   "source": [
    "## 数组操作（添加，删除，去重）\n",
    "\n",
    "- TBD"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eaae6924",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 3 2 7 5 4]\n",
      "[1 2 7 5 4]\n",
      "[1 2 4 5 7]\n"
     ]
    }
   ],
   "source": [
    "x = np.array([1,3,2,7,5])\n",
    "# add an element\n",
    "x = np.append(x,4)\n",
    "print(x)\n",
    "\n",
    "# delete an element \n",
    "# np.delete(ndarray, pos)\n",
    "x = np.delete(x,1)\n",
    "print(x)\n",
    "\n",
    "# sort\n",
    "x = np.sort(x)\n",
    "print(x)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f902857a",
   "metadata": {},
   "source": [
    "## 生成随机数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "354d1c66",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "18"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# np.random.randint(low, high, size)\n",
    "# 返回一个随机整型数，范围从低（包括）到高（不包括），即[low, high)。\n",
    "# 如果没有写参数high的值，则返回[0,low)的值。\n",
    "\n",
    "np.random.randint(19)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "724238b0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "numpy.ndarray"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# set seed \n",
    "# np.random.seed()\n",
    "np.random.seed(200)\n",
    "np.random.randint(0,20,(2,2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "3864539b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.5812246790465982"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.random.randn(d0,d1,d2……dn)  \n",
    "# 返回一个或一组服从标准正态分布的随机样本值\n",
    "'''\n",
    "1)当函数括号内没有参数时，则返回一个浮点数； \n",
    "2）当函数括号内有一个参数时，则返回秩为1的数组，不能表示向量和矩阵； \n",
    "3）当函数括号内有两个及以上参数时，则返回对应维度的数组，能表示向量或矩阵； \n",
    "4）np.random.standard_normal（）函数与np.random.randn()类似，但是np.random.standard_normal（）\n",
    "的输入参数为元组（tuple）. \n",
    "5)np.random.randn()的输入通常为整数，但是如果为浮点数，则会自动直接截断转换为整数。\n",
    "'''\n",
    "import numpy as np\n",
    "np.random.randn()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "de19d948",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0.1473907 , 0.76030289, 0.70901455, 0.98915244, 0.34383313,\n",
       "        0.41101535, 0.45878172, 0.96916191, 0.1946141 , 0.88539065],\n",
       "       [0.8883605 , 0.3567964 , 0.7972337 , 0.22489521, 0.79485016,\n",
       "        0.55984639, 0.65734365, 0.40190371, 0.66727272, 0.93720887]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.random.random() # 0到1 的浮点数\n",
    "np.random.random((2,10))  # input 为 tuple\n",
    "\n",
    "# 同 numpy.random.rand(d0, d1, …, dn)\n",
    "# 返回的随机样本位于[0, 1)中\n",
    "np.random.rand(2,10)  #input 不是 tuple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2c739804",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0 1 4]\n",
      " [1 0 2]]\n",
      "[3 2 0]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array(['pooh', 'pooh', 'Christopher', 'pooh', 'piglet'], dtype='<U11')"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.random.choice(a, size=None, replace=True, p=None)\n",
    "# 从一个给定的一维数组, 生成一个随机样本\n",
    "# a: 1-D array or int\n",
    "# If a is an int, the random sample is generated as if a were np.arange(a)\n",
    "# size : int or tuple of ints, optional\n",
    "print(np.random.choice(5,(2,3)))\n",
    "\n",
    "print(np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0]))\n",
    "\n",
    "pool = ['pooh', 'rabbit', 'piglet', 'Christopher']\n",
    "np.random.choice(pool, 5, p=[0.5, 0.1, 0.1, 0.3])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "9d392946",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1 3 8 9 7 5 2 0 6 4]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[0, 1, 2],\n",
       "       [6, 7, 8],\n",
       "       [3, 4, 5]])"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.random.shuffle(x)\n",
    "# 改变顺序, 类似洗牌，打乱顺序\n",
    "\n",
    "arr = np.arange(10)\n",
    "np.random.shuffle(arr)\n",
    "print(arr)\n",
    "\n",
    "# This function only shuffles the array along the first index of a multi-dimensional array\n",
    "\n",
    "arr = np.arange(9).reshape((3, 3))\n",
    "np.random.shuffle(arr)\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "f228a25e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([5, 1, 8, 2, 6, 3, 0, 9, 4, 7])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# np.random.permutation(x)\n",
    "# x : int or array_like\n",
    "# 返回一个随机排列\n",
    "# f x is a multi-dimensional array, it is only shuffled along its first index\n",
    "\n",
    "np.random.permutation(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0004720f",
   "metadata": {},
   "source": [
    "## 读取和存储数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f505d834",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "#changing_rate=np.load('changing_rate.npy').tolist()\n",
    "# np.save   np.load\n",
    "# np.savetxt    np.loadtxt   csv格式"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
